package com.hb.trade.server.project.section.service.raw.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.project.opening.entity.BidOpeningSchedule;
import com.hb.core.pojo.project.opening.mapper.BidOpeningScheduleMapper;
import com.hb.core.pojo.project.section.dto.BidSectionOfferDTO;
import com.hb.core.pojo.project.section.dto.BidSectionOfferListDTO;
import com.hb.core.pojo.project.section.dto.SectionOfferSearchDTO;
import com.hb.core.pojo.project.section.entity.BidSectionOffer;
import com.hb.core.pojo.project.section.mapper.BidSectionOfferMapper;
import com.hb.trade.server.project.opening.service.BidOpeningScheduleService;
import com.hb.trade.server.project.section.service.raw.BidSectionOfferDetailService;
import com.hb.trade.server.project.section.service.raw.BidSectionOfferService;
import com.hb.trade.server.project.util.DateUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 供应商标段报价表 服务实现类
 * </p>
 *
 * @author zhaojk
 * @since 2021-10-13
 */
@Service
public class BidSectionOfferServiceImpl extends ServiceImpl<BidSectionOfferMapper, BidSectionOffer> implements BidSectionOfferService {

    protected final BidSectionOfferDetailService bidSectionOfferDetailService;

    protected final BidOpeningScheduleService bidOpeningScheduleService;

    public BidSectionOfferServiceImpl(BidSectionOfferDetailService bidSectionOfferDetailService,
                                      BidOpeningScheduleService bidOpeningScheduleService
    ) {
        this.bidSectionOfferDetailService = bidSectionOfferDetailService;
        this.bidOpeningScheduleService = bidOpeningScheduleService;
    }

    @Override
    public Integer getLastOffer(Long offerId, Long sectionId) {
        QueryWrapper<BidSectionOffer> wrapperOffer = BidSectionOffer.wrapper();
        wrapperOffer.eq(null != offerId, "offer_id", offerId).eq("section_id", sectionId);
        wrapperOffer.orderByDesc("create_time");
        wrapperOffer.last("limit 1");
        BidSectionOffer sectionOffer = getOne(wrapperOffer);
        if (sectionOffer == null) {
            return 0;
        }
        return sectionOffer.getOfferOrder();
    }

    @Override
    public String getLastOfferParamValue(Long offerId, Long sectionId) {
        QueryWrapper<BidSectionOffer> wrapperOffer = BidSectionOffer.wrapper();
        wrapperOffer.eq("offer_id", offerId).eq("section_id", sectionId).isNotNull("param_value");
        wrapperOffer.orderByDesc("offer_order");
        wrapperOffer.last("limit 1");
        BidSectionOffer sectionOffer = getOne(wrapperOffer);
        if (sectionOffer == null) {
            return "0";
        }
        return sectionOffer.getParamValue();
    }

    @Override
    public List<Integer> getOfferOrder(Long sectionId) {
        return baseMapper.getOfferOrder(sectionId);
    }

    @Override
    public List<BidSectionOfferListDTO> listOfferByTender(SectionOfferSearchDTO sectionOfferSearch) {
        List<BidSectionOfferListDTO> vos = CollUtil.list(false);
        // TODO 根据标段ID查询所有计划明细信息
        // List<PurchasePlanInfo> planInfos = planInfoService.findBySectionId(sectionOfferSearch.getSectionId());
        // TODO 获取所有明细ID集合
        // List<Long> planInfoIds = planInfos.stream().map(PurchasePlanInfo::getId).collect(Collectors.toList());

        //判断标段是否有计划明细
//        if (planInfoIds.size() > 0) {
            if (Objects.equals(sectionOfferSearch.getType(), "1")) {//1无报价   只需要传明细列表
                // TODO 拼接无报价的明细列表
                // List<PurchasePlanInfoDTO> purchasePlanInfoVOList = getPurchasePlanInfoVOList(planInfos);
                // vos.add(BidSectionOfferListDTO.packagePlanInfo(0, purchasePlanInfoVOList));
            } else if (Objects.equals(sectionOfferSearch.getType(), "2")) {//2含报价   需要拼接报价
                // 查询指定供应商和明细ID的报价
                QueryWrapper<BidSectionOffer> wrapperOffer = BidSectionOffer.wrapper();
                wrapperOffer.eq("section_id", sectionOfferSearch.getSectionId());

                if (sectionOfferSearch.getOfferOrder() != null && sectionOfferSearch.getOfferOrder() > 0) {
                    Integer offerOrder = sectionOfferSearch.getOfferOrder();
                    // 查询最大的轮次, 如果参数大于最大的轮次, 则取最大轮次值
                    Integer lastOffer = getLastOffer(null, sectionOfferSearch.getSectionId());
                    if (offerOrder.compareTo(lastOffer) > 0) {
                        offerOrder = lastOffer;
                    }

                    // TODO 如果传入了轮次的参数就查询指定轮次
//                    wrapperOffer.eq("`offer_order`", offerOrder);
//                    BidSectionOfferListVo assemblyList = getAssemblyList(sectionOfferSearch, planInfos,
//                            BidSectionOfferListVo.packageOrder(offerOrder));
//                    vos.add(assemblyList);

                } else {
                    // 查询投标人所有轮次价格，并拼接
                    List<Integer> offerOrder = baseMapper.getOfferOrder(sectionOfferSearch.getSectionId()); //获取指定标段的所有轮次
                    for (Integer integer : offerOrder) {
                        wrapperOffer.eq("offer_order", integer);
                        sectionOfferSearch.setOfferOrder(integer);
//                        TODO
//                        BidSectionOfferListVo assemblyList = getAssemblyList(sectionOfferSearch, planInfos,
//                                BidSectionOfferListVo.packageOrder(integer));
//                        vos.add(assemblyList);
                    }
                }
            } else {
                // TODO: 2021/10/14 对比价
            }
//        }
        return vos;
    }

    /**
     * 根据查询条件查询报价列表
     *
     * @param sectionOfferSearch 查询VO
     * @return 报价列表
     */
    @Override
    public List<BidSectionOffer> getOfferList(SectionOfferSearchDTO sectionOfferSearch) {
        QueryWrapper<BidSectionOffer> wrapperOffer = BidSectionOffer.wrapper();
        wrapperOffer.eq("section_id", sectionOfferSearch.getSectionId());
        if (StringUtils.isNotEmpty(sectionOfferSearch.getOfferId())) {
            wrapperOffer.eq("offer_id", sectionOfferSearch.getOfferId());
        }
        if (sectionOfferSearch.getOfferOrder() != null && sectionOfferSearch.getOfferOrder() > 0) {
            wrapperOffer.eq("offer_order", sectionOfferSearch.getOfferOrder());
        }
        return baseMapper.selectList(wrapperOffer);
    }

    /**
     * 获取最后一次报价（轮询）
     *
     * @param offerId   投标人ID
     * @param sectionId 标段ID
     * @return
     */
    @Override
    public BidSectionOffer getLastBidSectionOffer(Integer turns, Long offerId, Long sectionId) {
        QueryWrapper wrapperOffer = new QueryWrapper();
        wrapperOffer.eq("offer_id",offerId.toString());
        wrapperOffer.eq("offer_order",turns);
        wrapperOffer.eq("section_id",sectionId.toString());
        BidSectionOffer bidSectionOffer = baseMapper.selectOne(wrapperOffer);
        return bidSectionOffer;
    }


    /**
     * Description: 供应商提交报价
     *
     * @param bidSectionOffer
     * @author: fengbin
     * @date: 2022/2/21 17:23
     * @return: java.lang.Boolean
     */
    @Override
    public Boolean legalSubmit(BidSectionOfferDTO bidSectionOffer) {
        List<BidSectionOfferDTO> bidSectionOfferDTOS = listOfferInfosByOffId(bidSectionOffer.getOfferId(), bidSectionOffer.getSectionId());
        Integer offerOrder = bidSectionOfferDTOS.get(0).getOfferOrder();
        if(ObjectUtils.isEmpty(bidSectionOffer.getOfferOrder())){
            //判断报价轮次与最新轮次是否相同  若不同则说明此轮报价已结束
            if (!offerOrder.equals(bidSectionOffer.getOfferOrder())){
                return false;
            }
        }
        // 判断本轮的报价是否已经截止
        if(bidSectionOfferDTOS.get(0).getEndTime().isBefore(LocalDateTime.now())) {
            return false;
        }
        //根据标段轮次及标段id 及投标人id修改报价价格
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("offer_id", bidSectionOffer.getOfferId().toString());
        queryWrapper.eq("offer_order", bidSectionOffer.getOfferOrder());
        queryWrapper.eq("section_id", bidSectionOffer.getSectionId().toString());
        //修改报价状态
        bidSectionOffer.setOfferType(2);
        int update = baseMapper.update(bidSectionOffer, queryWrapper);
        return update > 0 ? true : false;
    }

    @Override
    public List<BidSectionOfferDTO> listOfferInfosByturns(Integer turns, Long sectionId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if(turns != null ){
            queryWrapper.eq("offer_order", turns);
        }
        queryWrapper.eq("section_id", sectionId.toString());
        List<BidSectionOffer> list = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<BidSectionOfferDTO> list1 = Convert.convert(new TypeReference<List<BidSectionOfferDTO>>() {}, list);
        return list1;
    }

    @Override
    public List<BidSectionOfferDTO> listOfferInfosByOffId(Long offerId, Long sectionId) {
        String tenderOfferUtil = null ;
        String tenderOfferName = null ;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("offer_id", offerId.toString());
        queryWrapper.eq("section_id", sectionId.toString());
        queryWrapper.orderByDesc("offer_order");
        List<BidSectionOfferDTO> list = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<BidSectionOfferDTO> list1 = Convert.convert(new TypeReference<List<BidSectionOfferDTO>>() {}, list);
        // 根据标段id 查询当前标段下的开标一览表信息（主要使用投标报价小写的单位）
        List<BidOpeningSchedule> bidOpeningSchedules = bidOpeningScheduleService.listBySectionId(sectionId);
        for (BidOpeningSchedule schedule : bidOpeningSchedules) {
            String bidOpeningName = schedule.getBidOpeningName();
            boolean res = bidOpeningName.contains("投标报价小写");
            if (res) {
                tenderOfferUtil = schedule.getUnitName();
                tenderOfferName = schedule.getBidOpeningName();
            }
        }
        for (BidSectionOfferDTO sectionOffer : list1) {
            sectionOffer.setTenderOfferLowUnit(tenderOfferUtil);
            sectionOffer.setTenderOfferName(tenderOfferName);
        }
        return list1;
    }

    @Override
    public Boolean updataExpertOpinionByOfferId(BidSectionOfferDTO bidSectionOffer) {
        if(ObjectUtils.isEmpty(bidSectionOffer.getOfferId()) || ObjectUtils.isEmpty(bidSectionOffer.getOfferOrder())){
            return false;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("offer_id", bidSectionOffer.getOfferId().toString());
        queryWrapper.eq("section_id", bidSectionOffer.getSectionId().toString());
        queryWrapper.eq("offer_order", bidSectionOffer.getOfferOrder());
        baseMapper.update(bidSectionOffer,queryWrapper);
        return true;
    }



}
